import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
	baseURL: '', // url = base url + request url
	timeout: 3000000 // request timeout
})

service.interceptors.request.use(
	config => {
		if (store.getters.token) {
			config.headers['X-Token'] = getToken()
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	response => {
		const res = response.data
		if (res.msgDesc === '成功') {
			res.ok = true
		}
		if (res.ok !== true && response.status !== 200) {
			Message({
				message: res.msgDesc || 'Error',
				type: 'error',
				duration: 5 * 1000
			})
		} else {
			return res
		}
	},
	error => {
		Message({
			message: error.message,
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service
